package com.chennan.javabase.domain.juc.forkjoin;

import java.util.concurrent.RecursiveTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author chennan
 * @create 2022-01
 *
 * 并行流 完成计算任务
 * 使用 forkjoin
 * 1、ForkJoinPool
 * 2、计算任务：forkjoinPool.execute(ForkJoinTask task)
 */
public class ForkJoinDemo extends RecursiveTask<Long> {

    public static AtomicLong atomicLong = new AtomicLong(0);

    public static final Long SUM_MAX = 1000000L;

    private Long start;
    private Long end;
    //临界值
    private Long temp = 10L;

    public ForkJoinDemo(Long start,Long end){
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        if((end-start)<temp){
            return executeTask(start,end);
        }else {
            long middle = (end+start)/2;
            ForkJoinDemo task1 = new ForkJoinDemo(start,middle);
            task1.fork();
            ForkJoinDemo task2 = new ForkJoinDemo(middle+1,end);
            task2.fork();
            return task1.join()+task2.join();
        }
    }

    private Long executeTask(Long start, Long end) {
        System.out.println("执行分叉合并任务:"+start+","+end+"线程活跃数："+Thread.activeCount());
        atomicLong.addAndGet((end-start)+1);
        try {
            TimeUnit.SECONDS.sleep((int)(Math.random()*4));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return 1L;
    }
}

